import java.util.Scanner;

/**
 * @author yu
 * @date 2025年04月19日 15:34
 */
/*class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}*/

public class _02_LinkedList_01_203removeElements {
    public ListNode removeElements(ListNode head,int val){
        // 设置一个虚拟的头结点
        ListNode dummy = new ListNode();
        dummy.next = head;

        ListNode cur = dummy;
        while (cur.next != null) {
            if (cur.next.val == val) {
                cur.next = cur.next.next;//直接指向下一个指针 curr不变 后续可以进入循环检查下一个val直到不等于target
            } else {
                cur = cur.next;
            }
        }
        return dummy.next;
    }

    // 根据数组创建链表
    public ListNode createLinkedList(int[] arr) {
        if (arr.length == 0) {
            return null;
        }
        ListNode head = new ListNode(arr[0]);
        ListNode current = head;
        for (int i = 1; i < arr.length; i++) {
            current.next = new ListNode(arr[i]);
            current = current.next;
        }
        return head;
    }

    // 打印链表
    public void printLinkedList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        _02_LinkedList_01_203removeElements solution = new _02_LinkedList_01_203removeElements();
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入链表节点的值，用空格分隔：");
        String input = scanner.nextLine();
        String[] valuesStr = input.split(" ");
        int[] values = new int[valuesStr.length];
        for (int i = 0; i < valuesStr.length; i++) {
            values[i] = Integer.parseInt(valuesStr[i]);
        }

        ListNode head = solution.createLinkedList(values);

        System.out.println("请输入要移除的节点值：");
        int val = scanner.nextInt();

        ListNode newHead = solution.removeElements(head, val);

        System.out.println("移除指定值后的链表为：");
        solution.printLinkedList(newHead);

        scanner.close();
    }
}


